package com.stone.weblog.common.exception;

import com.stone.weblog.common.enums.ResponseCodeEnum;
import com.stone.weblog.common.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @program: weblog-springboot
 * @author: stone
 * @url: 1755545704@qq.com
 * @create: 2024-01-14 14:57
 * @description: 全局异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExcEptionHandler {

    /**
    * @Description: 捕获自定义业务异常
    * @Param: [request, e]
    * @return: com.stone.weblog.common.response.Response<java.lang.Object>
    * @Author: stone
    * @Date: 2024/1/14 15:01
    */
    @ResponseBody
    @ExceptionHandler({BizException.class})
    public Response<Object> handleBizException(HttpServletRequest request,BizException e){
        log.warn("{} request fail, errorCode: {}, errorMessage: {}", request.getRequestURI(), e.getErrorCode(), e.getErrorMessage());
        return Response.fail(e);
    }


    @ResponseBody
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Response<Object> handleMethodArgumentNotValidException(HttpServletRequest request,MethodArgumentNotValidException e){
        String code = ResponseCodeEnum.PRODUCT_NOT_POUND.getErrorCode();
        BindingResult bindingResult =e.getBindingResult();
        StringBuilder sb=new StringBuilder();
        Optional.ofNullable(bindingResult.getFieldErrors()).ifPresent(errors -> {
            errors.forEach(error ->
                    sb.append(error.getField())
                            .append(" ")
                            .append(error.getDefaultMessage())
                            .append(",当前值：' ")
                            .append(error.getRejectedValue())
                            .append("';")
            );
        });

        String errorMessage= sb.toString();
        log.warn("{} request error, errorCode: {}, errorMessage: {}", request.getRequestURI(), code, errorMessage);

        return Response.fail(code, errorMessage);
    }

    /**
    * @Description:  捕获其他类型的异常代码
    * @Param: [request, e]
    * @return: com.stone.weblog.common.response.Response<java.lang.Object>
    * @Author: stone
    * @Date: 2024/1/14 15:37
    */
    @ResponseBody
    @ExceptionHandler({Exception.class})
    public Response<Object> handleOtherException(HttpServletRequest request,Exception e){
        log.error("{} request error, ", request.getRequestURI(), e);
        return Response.fail(ResponseCodeEnum.SYSTEM_ERROR);
    }
}